﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace LightingTcpService
{
    public class WorkbookParser
    {
        private byte[] _file;
        public WorkbookParser(byte[] file)
        {
            _file = file;
        }

        public WorkbookModel Parse()
        {
            WorkbookModel workbookModel = new WorkbookModel();
            foreach (CompressItem item in ZipHelper.UncompressZipFile(_file))
            {
                if (item.Name == "Relation.txt")
                {
                    using (MemoryStream ms = new MemoryStream(item.Stream))
                    {
                        StreamReader reader = new StreamReader(ms);
                        string jsonText = reader.ReadToEnd();
                        List<ImageModel> modeList = SerializeHelper.ConvertFromJson<List<ImageModel>>(jsonText);
                        workbookModel.ImageModels.AddRange(modeList);
                        ms.Close();
                    }
                }
                else
                {
                    if (Regex.IsMatch(item.Name, @"(xls|xlsx)$", RegexOptions.IgnoreCase))
                    {
                        workbookModel.ExcelFile = item;
                    }
                    else if (Regex.IsMatch(item.Name, @"(bmp|jpg|gif|png)$", RegexOptions.IgnoreCase))
                    {
                        workbookModel.ImageFiles.Add(new ImageFile() { Name = item.Name, File = item.Stream });
                    }
                }
            }
            return workbookModel;
        }
    }
}
